/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Logica;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 *
 * @author Diego
 */
@ServerEndpoint("/endpoint")
//@ServerEndpoint(value="/endpoint", encoders = {WSEncoder.class}, decoders =
//        {WSDecoder.class})
public class WSEndpoint {

    //guardamos la session de los usuarios, debe ser static 
    private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
    
     
    @OnMessage
    public void onMessage(String str, Session session) throws IOException {
        String userName = (String) session.getUserProperties().get("username");
        /*if(userName == null){
        
            userSession.getUserProperties().put("username", str);
            try {
                userSession.getBasicRemote().sendText(buildJsonData("System", "estas conectado como " + str));
            } catch (IOException ex) {
                Logger.getLogger(WSEndpoint.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else{
            for (Session openSession : sessions)
            {
                openSession.getBasicRemote().sendText(buildJsonData(userName, str));
            }
        }*/
        System.out.println("Se ha recibido un mensaje: " + str + "Usuario:" + userName + "sessiones: " + sessions.size());
        for (Session openSession : sessions) {
            if (openSession != session){
                openSession.getBasicRemote().sendText(str);
            }
          //  openSession.getBasicRemote().sendText(buildJsonData("UsuarioTest", str));
        }

    }
    
     @OnOpen
    public void onOpen(Session session){
      sessions.add(session);
    }
    
    @OnClose
    public void onClose(Session session){
        sessions.remove(session);
    }
    
  /*  private String buildJsonData(String username, String mensaje){
        JsonObject jsonObject = Json.createObjectBuilder().add("message", username+": "+mensaje).build();
        StringWriter stringWriter = new StringWriter();
        try(JsonWriter jsonWriter = Json.createWriter(stringWriter)) {jsonWriter.write(jsonObject);}
        return stringWriter.toString();
    }*/
}
